package com.lujianfei.redpacketstat.ui

import android.app.AlertDialog
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.EditText
import android.widget.Toast
import androidx.annotation.Nullable
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.lifecycle.Observer
import com.lujianfei.redpacketstat.Constant
import com.lujianfei.redpacketstat.R
import com.lujianfei.redpacketstat.base.BaseActivity
import com.lujianfei.redpacketstat.databinding.ActivityMainBinding
import com.lujianfei.redpacketstat.manager.MessageManager
import com.lujianfei.redpacketstat.manager.NotifyListener
import com.lujianfei.redpacketstat.ui.viewmodel.MainViewModel
import com.lujianfei.redpacketstat.utils.AppVersion
import org.koin.android.ext.android.inject


class MainActivity : BaseActivity<ActivityMainBinding>(), NotifyListener {

    private var checkTotal: MenuItem? = null
    private val mViewModel: MainViewModel by inject()
    private var tabString = arrayOf("未处理", "已处理") //定义一个数组存放标题内容
    private var fragments = ArrayList<MainFragment>()
    private var adapter:Adapter?= null

    override fun layoutId(): Int {
        return R.layout.activity_main
    }

    override fun initData() {
        Log.d("VIEWMODEL==", " MainActivity mViewModel=$mViewModel")
        MessageManager.instance.addListener(this)
        mViewModel.uiState.observe(this, Observer{
            state->
            if(state.loading) {
                dataBinding?.progressBar?.visibility = View.VISIBLE
            } else {
                dataBinding?.progressBar?.visibility = View.GONE
            }
            state.showToast?.let {
                showToast(it)
            }
            if (state.refreshUI) {
                fragments.forEach {
                    it.notifyUpdate()
                }
            }
        })
        fragments.add(MainFragment.newInstance(Constant.STATUS_UNPROCESSED))
        fragments.add(MainFragment.newInstance(Constant.STATUS_PROCESSED))
        adapter = Adapter(supportFragmentManager, fragments, tabString) //参数1为fragment管理器
        dataBinding?.viewPager?.adapter = adapter //给viewPager设置适配器
        dataBinding?.tabLayout?.setupWithViewPager(dataBinding?.viewPager) //将tabLayout与viewPager建立匹配
    }

    private fun updateMoreVisible() {
        checkTotal?.isVisible = mViewModel.amountVisibility() == View.VISIBLE
    }

    override fun initView() {
        setSupportActionBar(dataBinding?.toolBar)
        supportActionBar.apply {
            title = "红包统计神器"
        }
    }

    override fun initEvent() {
        val childAt = dataBinding?.toolBar?.getChildAt(0)
        childAt?.setOnClickListener {
            mViewModel.toolBarClick()
        }
    }

    //创建一个内部类作为适配器
    class Adapter(
        fm: FragmentManager,
        private val list: List<Fragment>,
        private var tabString: Array<String>
    ) :
        FragmentPagerAdapter(fm) {
        override fun getItem(position: Int): Fragment {
            return list[position]
        }

        override fun getCount(): Int {
            return list.size
        }

        //重写getPageTitle()方法，获取页标题
        @Nullable
        override fun getPageTitle(position: Int): CharSequence? {
            return tabString[position]
        }

    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_home, menu)
        checkTotal = menu?.findItem(R.id.action_checktotal)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.action_add -> {
                showInput() {
                    mViewModel.addUser(it)
                }
            }
            R.id.action_checktotal->{
                showStatics()
            }
            R.id.action_about->{
                showAbout()
            }
        }
        return super.onOptionsItemSelected(item)
    }

    private fun showStatics() {
        mViewModel.getTotalStatics {
            AlertDialog.Builder(this)
                .setTitle("红包统计")
                .setMessage(it)
                .setPositiveButton("确定",null)
                .show()
        }
    }

    private fun showAbout() {
        val sb = StringBuilder()
        sb.append("应用：${AppVersion.getAppName()}\n")
        sb.append("作者：陆小霏\n")
        sb.append("版本：${AppVersion.getVersionName()}\n")
        AlertDialog.Builder(this)
            .setTitle("关于")
            .setMessage(sb)
            .setPositiveButton("确定",null)
            .show()
    }

    private fun showInput(callback:(name:String)->Unit) {
        val editText = EditText(this)
        AlertDialog.Builder(this)
            .setTitle("请输入姓名")
            .setView(editText)
            .setPositiveButton("确定"
            ) { _, _ ->
                if (editText.text.isEmpty()) {
                    showToast("姓名不能为空!")
                } else {
                    callback(editText.text.toString())
                }
            }
            .setNegativeButton("取消",null)
            .show()
    }

    private fun showToast(text:String) {
        Toast.makeText(this,text,Toast.LENGTH_SHORT).show()
    }

    override fun onTabDataChange(unHandleCount: Int, handleCount: Int) {
        tabString[0] = "未处理($unHandleCount)"
        tabString[1] = "已处理($handleCount)"
        adapter?.notifyDataSetChanged()
    }

    override fun onDestroy() {
        MessageManager.instance.removeListener(this)
        super.onDestroy()
    }
}
